// components/Goods/goods.js
const app = getApp(),
  {
    $resHost
  } = app.globalData,
  _ = require('../../pages/Common/underscore.js');
const {
  homeNavigate
} = require('../../pages/Common/util');
var that;
let intervalStop = undefined;
let endTimeOver = '';
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isLimit: {
      type: Boolean,
      value: false
      // observer() {
      //     console.log('=====',this.data.isLimit)
      //     // this.getQrcode();
      // }
    },
    authoriz: {
      type: Boolean,
      value: false
    },
    isBrokerage: {
      type: Boolean,
      value: true
    },
    shareEmployeeId: {
      type: String,
      value: ''
      // observer() {
      //     this.getQrcode();
      // }
    },
    shareUserId: {
      type: String,
      value: ''
      // observer(){
      //     this.getQrcode();
      // }
    },
    actList: {
      type: Array,
      value: {},
      observer(actList) {}
    },
    uid: {
      type: String,
      value: ''
    },
    tabStatus: {
      type: Number,
      value: ''
    },
    goldtype: {
      type: String,
      value: ''
    },
    // isStaff: {
    //     type: String,
    //     value: ''
    // },
    surplusgold: {
      type: Number,
      value: 0
    },
    eid: {
      type: String,
      value: ''
    },
    goodsInfo: {
      type: Object,
      value: {},
      observer(goodsInfo) {
        let {
          classId = '0',
          id
        } = goodsInfo;
        // console.log('111===',this.data.isLimit)
        // console.log(goodsInfo)
        if (goodsInfo.sku && goodsInfo.sku.length != '0') {
          goodsInfo.sku.find(p => {
            if (p.goodsFlashSale && p.goodsFlashSale.isGoodsFlashSale) {
              this.setData({
                hasFlashSale: p.goodsFlashSale.isGoodsFlashSale
              });
            }
          });
        }
        // console.log(this.data.hasFlashSale)
        if (!(Object.keys(goodsInfo).length == 0) && this.data.isLimit) {
          var oDate = new Date(); //获取现在日期对象

          // console.log(goodsInfo)

          if (JSON.stringify(goodsInfo.flashSale) === '[]' || JSON.stringify(goodsInfo.flashSale) === '{}') {
            goodsInfo.flashSale = {
              timeStatus: 3
            };
            this.setData({
              isActive: true //是否有活动true就是无
            });
          }
          var oldYear = oDate.getFullYear();
          // console.log(oDate.getFullYear())
          endTimeOver = `${oldYear}-${goodsInfo.flashSale.endTimeFormat}`;
          endTimeOver = endTimeOver.replace(/-/g, '/');
          // type = [1=打折,2=减免]
          if (goodsInfo.flashSale.type == 1) {
            // goodsInfo.flashSale.preferentialPrice = goodsInfo.flashSale.price*(item.preferential*0.1)
          }
          this.setData({
            detailBuy: goodsInfo.flashSale,
            goodsStock: goodsInfo.sku[0].stock
          });
          if (goodsInfo.flashSale.timeStatus == 2) this.getDate();
        }
        if (classId !== '0') {
          const url = getCurrentPages().pop().route === 'independentNewGoods/Goods/index' ? '/user/goods-attr/ec-get-attr-list' : '/user/goods-attr/get-attr-list';
          app.$getData(url, {
            classId,
            goodsId: id
          }).then(data => {
            this.setGoods(goodsInfo, data.data || []);
          });
        }
        if (typeof id != 'undefined' && goodsInfo.enableSplicingPattern == '1') {
          this.getSuccessData();
        }
        // this.getQrcode();
      }
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    authoriz: false,
    isActive: false,
    oneIcon: `${$resHost}/img/miniprogram/kill/limitBg.png`,
    limitText: `${$resHost}/img/miniprogram/kill/limit.png`,
    residue: `${$resHost}/img/miniprogram/kill/residue.png`,
    M_icon: `${$resHost}/img/miniprogram/Tweet/z5.png`,
    stock: `${$resHost}/img/miniprogram/kill/stock.png`,
    received: `${$resHost}/img/miniprogram/kill/received.png`,
    like: `${$resHost}/img/miniprogram/kill/like.png`,
    indicatorDots: true,
    vertical: false,
    autoplay: false,
    wrap: 100,
    tab: {
      img: 0
    },
    transform: '',
    interval: 2000,
    duration: 500,
    appQrcode: '',
    goodsId: '',
    status: '',
    panoramaImg: `${$resHost}/img/cases/360.png`,
    //全景
    imgToggle: false,
    //是否显示图片按钮
    mainPic: [],
    detailPic: [],
    auditLog: [],
    //审核日志
    goodsName: "",
    goodsJingle: "",
    goodsMarketprice: "",
    userIntegral: "",
    goodsPrice: "",
    saleGoodsPrice: "",
    goodsIntegral: "",
    goodsBody: "",
    goodsSerial: "",
    goodsClick: "",
    goodsSalenum: "",
    goodsCollect: "",
    goodsView: "",
    deposit: '',
    payType: '',
    evaluationCount: "",
    goodsStock: "",
    goodsState: "",
    goodsSelltime: "",
    goodsDowntime: "",
    goodsAddtime: "",
    goodsEdittime: "",
    goodsUnit: "",
    isNeedPrice: true,
    goodsVat: true,
    isFreeShip: true,
    //商品属性
    props: [],
    //商品规格
    toggle: false,
    videoUrl: '',
    panoramaUrl: '',
    goodsType: '',
    beginTime: '',
    endTime: '',
    cityName: '',
    spec: [],
    video: {},
    deliveryType: '',
    orgId: '',
    detailMedia: '',
    detailBuy: {},
    //显示抢购数据
    timeOver: false,
    enableSplicingPattern: '',
    twoIcon: `${$resHost}/img/miniprogram/kill/kill-2.jpg`,
    successData: [],
    autoplay: true,
    circular: true,
    vertical: true,
    interval: 3000,
    duration: 500,
    itemLength: 3,
    itemHeight: '450rpx',
    unpaidOrderId: '',
    times: ['00', '00', '00', '00'],
    spreadActivityId: '0',
    minSku: {},
    hasFlashSale: false,
    minPrice: 0
  },
  created() {
    that = this;
    that.setData({
      isDisplay: xhs.getStorageSync('config').wechatInfo.showOrgInfo == '2' ? false : true
    });
  },
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
    },
    detached: function () {
      clearInterval(intervalStop);

      // 在组件实例被从页面节点树移除时执行
    }
  },
  pageLifetimes: {
    show: function () {
      // 页面被展示
      //   console.log('页面被展示')

      //   if(this.data.isLimit){
      //     this.getDate();
      //   }
    },
    hide: function () {
      // console.log('guanb')
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    clickInfo() {
      console.log(1111);
      this.triggerEvent('myevent', '123456我我我');
    },
    getDate() {
      var obj = null;
      var countDownArr = [];
      var oDate = new Date(); //获取现在日期对象
      var oldTime = oDate.getTime(); //现在距离1970年的毫秒数
      var oldYear = oDate.getFullYear();
      // console.log(oDate.getFullYear())
      var newDate = new Date(endTimeOver); //获取指定日期对象

      var newTime = newDate.getTime(); //2018年距离1970年的毫秒数
      var second = Math.floor((newTime - oldTime) / 1000); //未来时间距离现在的秒数
      var day = Math.floor(second / 86400); //整数部分代表的是天；一天有24*60*60=86400秒 ；
      second = second % 86400; //余数代表剩下的秒数；
      var hour = Math.floor(second / 3600); //整数部分代表小时；
      second %= 3600; //余数代表 剩下的秒数；
      var minute = Math.floor(second / 60);
      second %= 60;

      // console.log(newTime - oldTime)
      // console.log(day)
      // console.log(hour)
      // console.log(minute)
      // console.log(second)

      if (day == '0' && hour == '0' && minute == '0' && second == '0') {
        clearInterval(intervalStop);
        that.setData({
          countDownList: [{
            day: "00",
            hou: "00",
            min: "00",
            sec: "00"
          }],
          timeOver: true
        });
        that.triggerEvent('addInfo', 'over');
        return;
      }
      if (newTime - oldTime < 0) {
        // console.log(6666)
        clearInterval(intervalStop);
        that.setData({
          countDownList: [{
            day: "--",
            hou: "--",
            min: "--",
            sec: "--"
          }]
        });
        that.triggerEvent('addInfo', '激素');
        return;
      }
      obj = {
        day: that.timeFormat(day),
        hou: that.timeFormat(hour),
        min: that.timeFormat(minute),
        sec: that.timeFormat(second)
      };
      countDownArr.push(obj);
      // console.log(countDownArr)

      that.setData({
        countDownList: countDownArr
      });
      clearInterval(intervalStop);
      intervalStop = setInterval(that.getDate, 1000); //
    },
    timeFormat(n) {
      return n >= 0 && n < 10 ? '0' + n : '' + n;
    },
    preView() {
      xhs.previewImage({
        current: this.data.appQrcode,
        // 当前显示图片的http链接
        urls: [this.data.appQrcode] // 需要预览的图片http链接列表
      });
    },
    getQrcode() {
      if (this.data.goodsInfo.id && (this.data.shareEmployeeId || this.data.shareUserId)) {
        //获取当前
        let param = {
          path: 'independentGoods/Goods/goods',
          params: {
            goodsId: this.data.goodsInfo.id,
            shareEmployeeId: this.data.shareEmployeeId,
            shareUserId: this.data.shareUserId
          }
        };
        app.$getData('/user/qrcode/get-wx-app-qrcode', param).then(data => {
          if (data.errCode == 0) {
            this.setData({
              appQrcode: data.appQrcode
            });
          }
        });
      }
    },
    preViewDetail(e) {
      let {
          url
        } = e.target.dataset,
        urls = this.data.detailPic.map(p => {
          return p.url;
        });
      xhs.previewImage({
        current: url,
        // 当前显示图片的http链接
        urls: urls // 需要预览的图片http链接列表
      });
    },
    preViewMain(e) {
      let {
          url
        } = e.target.dataset,
        urls = this.data.mainPic.map(p => {
          return p.url;
        });
      xhs.previewImage({
        current: url,
        // 当前显示图片的http链接
        urls: urls // 需要预览的图片http链接列表
      });
    },
    switchTab(e) {
      let {
          tab
        } = e.target.dataset,
        {
          wrap
        } = this.data,
        video = xhs.createVideoContext('goodsVideo', this);
      this.setData({
        transform: this.data.tab[tab]
      });
      video.pause();
    },
    /**
    * @api 获取素材推荐列表
    * @param int activityType 活动类型[20=秒杀,4=砍价,110=心愿购,=众筹,108=拼团,8=商品]
    * @param int activityId 活动ID
    * @param int currentPage 当前页
    * @param int pageSize 每页数量
    */
    getActivities() {
      app.$getData('/user/material/get-recommend-list', {
        activityType: 8,
        activityId: this.data.goodsInfo.id
      }).then(data => {
        if (data.errCode == 0) {
          this.setData({
            actList: data.data
          });
        } else {
          xhs.showModal({
            title: '提示',
            content: data.errInfo,
            showCancel: false,
            success: () => {}
          });
        }
      });
    },
    setGoods(goodsInfo, attrVals) {
      let goodsProp = goodsInfo.prop,
        tab = {
          img: 0
        },
        wrap = 100,
        imgToggle = false;
      delete goodsInfo.classId;
      //获取小程序二维码
      //计算宽度
      if (goodsInfo.videoUrl) {
        tab.video = 0;
        tab.img = -100;
        tab.panorama = -200;
        wrap += 100;
        imgToggle = true;
      } else if (goodsInfo.panoramaUrl) {
        imgToggle = true;
        tab.panorama = -100;
      }
      if (goodsInfo.panoramaUrl) {
        wrap += 100;
      }
      let videoDate = {
        cover: goodsInfo.videoImageId != '0' ? goodsInfo.videoImage.url : goodsInfo.video.cover || '',
        url: goodsInfo.video.url || '',
        materialId: goodsInfo.video.materialId || ''
      };
      //判断是否是总部积分商品，是取积分不是取金币
      let goldNum = !goodsInfo.isTopOrg ? goodsInfo.userIntegralCu : goodsInfo.userIntegral;
      goldNum = goodsInfo.exchangeType == '1' ? goodsInfo.userIntegralStaff : goldNum;
      this.setData({
        imgToggle,
        wrap,
        tab,
        auditLog: goodsInfo.auditLog || '',
        beginTime: goodsInfo.beginTime || '',
        endTime: goodsInfo.endTime || '',
        cityName: (goodsInfo.areasInfo || []).join(),
        goodsType: goodsInfo.goodsType || '',
        detailPic: goodsInfo.detailPic,
        evaluationCount: goodsInfo.evaluationCount,
        goodsAddtime: goodsInfo.goodsAddtime,
        goodsClick: goodsInfo.goodsClick,
        goodsCollect: goodsInfo.goodsCollect,
        goodsEdittime: goodsInfo.goodsEdittime,
        goodsJingle: goodsInfo.goodsJingle,
        goodsMarketprice: goodsInfo.goodsMarketprice,
        userIntegral: goldNum,
        goodsName: goodsInfo.goodsName,
        goodsSalenum: goodsInfo.goodsSalenum,
        goodsState: goodsInfo.goodsState,
        goodsUnit: goodsInfo.goodsUnit,
        goodsVat: goodsInfo.goodsVat,
        goodsView: goodsInfo.goodsView,
        deposit: goodsInfo.deposit,
        payType: goodsInfo.payType,
        isFreeShip: goodsInfo.isFreeShip,
        isNeedPrice: goodsInfo.isNeedPrice,
        mainPic: goodsInfo.mainPic,
        deliveryType: goodsInfo.deliveryType,
        enableSplicingPattern: goodsInfo.enableSplicingPattern,
        panoramaUrl: encodeURIComponent(goodsInfo.panoramaUrl),
        //全景
        video: {
          url: goodsInfo.videoUrl,
          //视频
          materialId: goodsInfo.videoCoverMaterial ? goodsInfo.videoCoverMaterial[0].materialId : '',
          cover: goodsInfo.videoCoverMaterial ? goodsInfo.videoCoverMaterial[0].thumb : ''
        },
        goodsBody: goodsInfo.goodsBody.replace(/(\n\r?)/g, '<br>').replace(/\s/g, '&nbsp;'),
        orgId: goodsInfo.orgId,
        detailMedia: videoDate,
        indicatorDots: goodsInfo.mainPic.length > 1 ? true : false
      });
      // 统计可选规格
      //
      var propAlias = goodsInfo.propAlias,
        specPic = goodsInfo.specPic,
        spec = [],
        //商品规格
        skuAttrId = [],
        //返回存在属性值
        skuAttrVal = _.chain(goodsInfo.sku).map(sku => {
          return sku.val;
        }).flatten(true).map(val => {
          skuAttrId.push(val.attrId);
          return val;
        }).value(),
        skuAttrValId;
      skuAttrId = _.uniq(skuAttrId);
      skuAttrValId = _.uniq(skuAttrVal.map(val => {
        return val.attrValId;
      }));
      skuAttrVal = skuAttrValId.map(valId => {
        return _.findWhere(skuAttrVal, {
          attrValId: valId
        });
      });
      spec = _.filter(attrVals, attr => {
        var index = ~skuAttrId.indexOf(attr.id),
          alias;
        if (index) {
          alias = propAlias.filter(al => {
            return al.attrId === attr.id;
          })[0] || {
            aliasName: attr.attrName
          };
          //处理属性值
          attr.attrName = alias.aliasName;
          attr.attrVal = skuAttrVal.filter(val => {
            var is = attr.id === val.attrId;
            val.pic = '';
            if (is) {
              //处理属性值对应的图片
              val.pic = (specPic.filter(pic => {
                return pic.attrValId === val.attrValId;
              })[0] || {
                url: ''
              }).url;
            }
            return is;
          });
        }
        return index;
      });

      //处理价格
      var goodsPrices = _.map(goodsInfo.sku, sku => {
          return Number(sku.price);
        }),
        maxPrice = _.max(goodsPrices),
        minPrice = _.min(goodsPrices);
      var goodsIntegrals = _.map(goodsInfo.sku, sku => {
          return Number(sku.integral);
        }),
        maxIntegral = _.max(goodsIntegrals),
        minIntegral = _.min(goodsIntegrals),
        maxIndex = goodsIntegrals.indexOf(maxIntegral),
        minIndex = goodsIntegrals.indexOf(minIntegral);
      // console.log(this.data.goldtype)
      let goldtypeName = !goodsInfo.isTopOrg ? '金币' : '积分';
      this.setData({
        spec: spec,
        goodsIntegral: maxIntegral === minIntegral ? (goodsInfo.sku[maxIndex].price != '0.00' && goodsInfo.sku[maxIndex].price ? '¥' + goodsInfo.sku[maxIndex].price + '+' : '') + maxIntegral + goldtypeName : (goodsInfo.sku[minIndex].price != '0.00' && goodsInfo.sku[minIndex].price ? '¥' + goodsInfo.sku[minIndex].price + '+' : '') + minIntegral + goldtypeName + '~' + ((goodsInfo.sku[maxIndex].price != '0.00' && goodsInfo.sku[maxIndex].price ? '¥' + goodsInfo.sku[maxIndex].price + '+' : '') + maxIntegral + goldtypeName),
        goodsPrice: maxPrice === minPrice ? maxPrice : minPrice + '~' + maxPrice,
        minPrice: minPrice,
        saleGoodsPrice: goodsInfo.maxValue === goodsInfo.minValue ? goodsInfo.maxValue : goodsInfo.minValue + '~' + goodsInfo.maxValue
      });
      let minSku = [];
      goodsInfo.sku.map(p => {
        if (p.price == minPrice) {
          minSku.push(p);
        }
      });
      minSku.sort(function (a, b) {
        return parseFloat(a.splicePrice) - parseFloat(b.splicePrice);
      });
      this.setData({
        minSku: minSku[0]
      });
      var imgUrl = this.data.mainPic[0] || {};
      //商品属性
      this.data.props = [];
      goodsProp.forEach(prop => {
        this.data.props.push({
          name: prop.attrName,
          id: prop.id,
          val: prop.customPropVal ? prop.customPropVal : prop.val.map(val => {
            return val.attrValName;
          }).join(',')
        });
      });
      this.setData({
        props: this.data.props
      });
    },
    goSeniorEdit(e) {
      const {
        url,
        link
      } = e.currentTarget.dataset;
      if (link) {
        xhs.navigateTo({
          url: homeNavigate(link, this.data.orgId)
        });
      } else {
        xhs.previewImage({
          current: url,
          // 当前显示图片的http链接
          urls: [url] // 需要预览的图片http链接列表
        });
      }
    },
    getSuccessData() {
      app.$getData('/user/ec-goods/get-splicing-list', {
        goodsId: this.data.goodsInfo.id,
        currentPage: 1,
        pageSize: 10
      }).then(data => {
        if (data.errCode == 0) {
          let itemLength = 1,
            itemHeight = '450rpx';
          if (data.data.length == 1) {
            itemLength = 1;
            itemHeight = '150rpx';
          } else if (data.data.length == 2) {
            itemLength = 2;
            itemHeight = '300rpx';
          } else if (data.data.length > 2) {
            itemLength = 3;
            itemHeight = '450rpx';
          }
          this.setData({
            itemLength: itemLength,
            itemHeight: itemHeight,
            successData: data.data
          });
        }
      });
    },
    setUpdate() {
      this.triggerEvent('sub');
    },
    spliceTapE(event) {
      this.triggerEvent('spliceTapE', {
        orderid: event.currentTarget.dataset.orderid,
        issplice: event.currentTarget.dataset.issplice
      });
    },
    goEvaluate() {
      let {
        goodsInfo
      } = this.data;

      // console.log(goodsInfo)
      // return
      xhs.navigateTo({
        url: `/independentNewGoods/evaluate/index?goodsId=${goodsInfo.id}`
      });
    },
    parseData(data, num) {
      return data.toFixed(num);
    }
  }
});